﻿using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;

public class TaskCancellationExample : MonoBehaviour
{
    private CancellationTokenSource _cts;

    async void Start()
    {
        CancellationTokenSource cts = new CancellationTokenSource();
        CancellationToken token = cts.Token;

        Task task = Task.Run(() =>
        {
            while (!token.IsCancellationRequested)
            {
                // 模拟耗时操作
                Thread.Sleep(500);
                Debug.Log("任务正在执行...");
            }

            token.ThrowIfCancellationRequested();
        }, token);

        // 模拟一段时间后取消任务
        await Task.Delay(2000);
        cts.Cancel();

        try
        {
            await task;
        }
        catch (OperationCanceledException)
        {
            Debug.Log("任务已取消");
        }

        Debug.Log("程序结束");
    }
}